package com.elvish.oda.busin.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.elvish.oda.busin.pojo.Menu;
import com.elvish.oda.busin.service.MenuService;
import com.fasterxml.jackson.core.JsonProcessingException;

@Controller
public class SysController {

	@Autowired
	private MenuService menuService;

	/**
	 * 初始化左侧菜单，目前只支持2级菜单
	 * 
	 * @return
	 * @throws JsonProcessingException
	 */
	@RequestMapping(value = "/sys/initMenu")
	public ModelAndView initMenu() throws JsonProcessingException {
		List<Menu> menus = menuService.findAll();
		List<Menu> chMenus = check(menus, SecurityUtils.getSubject());
		Map<Integer, Menu> temp = new HashMap<Integer, Menu>();
		for (Menu menu : chMenus) {
			temp.put(menu.getId(), menu);
		}

		List<Menu> rootMenus = new ArrayList<Menu>();
		for (Menu menu : chMenus) {

			Menu parent = temp.get(menu.getPid());
			if (parent == null) {
				rootMenus.add(menu);
			} else {
				List<Menu> children = parent.getChildren();
				if (children == null) {
					children = new ArrayList<Menu>();
					parent.setChildren(children);
				}

				children.add(menu);
			}
		}

		ModelAndView view = new ModelAndView("/main/index");
		view.addObject("menus", rootMenus);
		return view;
	}

	/**
	 * 检查用户是否有菜单权限
	 * 
	 * @param menus
	 *            所有菜单
	 * @param subject
	 *            shiro用户信息
	 * @return 用户已分配的菜单集合
	 */
	private List<Menu> check(List<Menu> menus, Subject subject) {
		List<Menu> res = new ArrayList<Menu>();
		for (Menu m1 : menus) {

			if (StringUtils.isEmpty(m1.getPermissionCode())) {
				continue;
			}
			if (subject.isPermitted(m1.getPermissionCode())) {
				res.add(m1);
			}
		}
		return res;
	}
}
